<template>
	<div>
		<el-dialog :title="titlecom" :visible.sync="dialogFormVisible" width="1300px">
			<!-- :rules="rules" -->
			<el-form :model="form" label-width="100px" class="demo-ruleForm">

				<el-form-item label="分类" :label-width="formLabelWidth" prop="copywritingtypeid">
					<el-select v-model="form.copywritingtypeid" placeholder="分类" class="specificationInput" filterable>
						<el-option v-for="a in reqCategory1" :key="a.id" :label="a.name" :value="a.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="水果or营销" :label-width="formLabelWidth" prop="shtype">
					<el-select v-model="form.shtype" placeholder="文案分类" filterable class="specificationInput">
						<el-option v-for="a in reqCategory2" :key="a.id" :label="a.name" :value="a.id"></el-option>
					</el-select>
				</el-form-item>

				<!-- 2024-5-20 hdd 新增label-标签字段 -->
				<el-form-item label="标签" :label-width="formLabelWidth" prop="label">
					<el-input v-model="form.label"></el-input>
				</el-form-item>

				<el-form-item label="轮播图" :label-width="formLabelWidth" prop="images">
					<el-upload action="" :http-request="uploadFile" list-type="picture-card"
						:on-preview="handlePictureCardPreview" :on-remove="handleRemove" multiple :file-list="imgList"
						:limit="10" class="avatar-uploader">
						<i class="el-icon-plus"></i>
					</el-upload>
					<el-dialog :visible.sync="dialogVisible1" :modal="false">
						<img width="100%" :src="dialogImageUrl" alt="" />
						<!-- <video
              controls="controls"
              width="100%"
              :src="dialogImageUrl"
              alt=""
              v-if="
                dialogImageUrl
                  .split('/')
                  [dialogImageUrl.split('/').length - 1].split('.')[1] != 'jpg'
              "
            /> -->
					</el-dialog>
					<draggable v-model="imgList" :options="{ handle: '.handle' }">
						<div v-for="(file, index) in imgList" :key="index" class="sortable-item">
							<i class="el-icon-menu handle"></i>
							<el-dialog :visible.sync="dialogVisible2" :modal="false">
								<img width="100%" :src="dialogImageUrl" alt="" class="sortable-img" />
							</el-dialog>
						</div>
					</draggable>

					<div class="lunboTag">
						建议尺寸：300*300，可拖拽改变图片顺序，默认首张图为主图，最多上传10张
					</div>
				</el-form-item>

				<el-form-item label="视频" :label-width="formLabelWidth" prop="video">
					<el-upload action="" :http-request="uploadFile1" list-type="picture-card"
						:on-preview="handlePictureCardPreview1" :on-remove="handleRemove1" :file-list="videolist"
						:show-file-list="false" :auto-upload="true" :accept="'.mp4'" class="avatar-uploader">
						<div v-if="videolist && videolist[0] && videolist[0].url">
							<video width="100%" controls="controls" style="width: 320px; height: 180px"
								:src="videolist[0].url"></video>
						</div>
						<i class="el-icon-plus" v-if="videolist.length != 1"></i>
					</el-upload>

					<!-- <div class="lunboTag">
            建议尺寸：300*300，可拖拽改变视频顺序，默认首张图为主图，最多上传10张
          </div> -->
				</el-form-item>
				<el-form-item label="文案" prop="content" :label-width="formLabelWidth" style="margin-top: 30px">
					<!-- <editor-bar
            v-model="form.content"
            :isClear="isClear"
            @change="change"
            style="width: 1000px; margin: 0"
          >
          </editor-bar> -->
					<el-input type="textarea" :rows="4" style="width: 547px" placeholder="请输入内容" v-model="form.content">
					</el-input>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="quedingtianjia()">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		addcopywritingadd,
		updatecopywritingupdate,
		gettypelist,
	} from "@/api/servetypeIndex";
	import {
		upload
	} from "@/api/editor.js";
	import EditorBar from "@/components/Editor";
	import draggable from "vuedraggable";
	export default {
		components: {
			EditorBar,
			draggable,
		},
		data() {
			return {
				reqCategory1: [],
				reqCategory2: [{
						id: 1,
						name: "水果文案"
					},
					{
						id: 2,
						name: "营销文案"
					},
				],
				isClear: false,
				dialogVisible: false,
				dialogFormVisible: false,
				formLabelWidth: "180px",
				form: {
					copywritingtypeid: "",
					content: "",
					images: "",
					shtype: "",
					video: "",
					label: ""
				},
				imgList: [],
				videolist: [],
				dialogImageUrl: "",
				dialogVideoUrl: "",
				dialogVisible1: false,
				dialogVisible2: false,
				dialogVisiblevideo: false,
				rules: {
					copywritingtypeid: [{
						required: true,
						message: "请选择分类",
						trigger: "blur"
					}, ],
					content: [{
						required: true,
						message: "请输入文案内容",
						trigger: "blur"
					}, ],
					images: [{
						required: true,
						message: "请上传图片",
						trigger: "blur",
					}, ],
					shtype: [{
						required: true,
						message: "请选择文案",
						trigger: "blur"
					}],
					video: [{
						required: true,
						message: "请上传视频",
						trigger: "blur"
					}],
				},
				qubie: 0,
			};
		},
		methods: {
			handlePictureCardPreview1(file) {
				this.dialogVideoUrl = file.url;
				this.dialogVisiblevideo = true;
				console.log(file);
			},
			//轮播图移除图片
			handleRemove1(file, fileList) {
				// fileList是剩下的照片
				this.videolist = fileList;
			},
			uploadFile1(param) {
				var file = param.file;
				const formData = new FormData();
				formData.append("file", file);
				upload(formData, param).then((res) => {
					this.videolist = [];
					if (res.code == 0) {
						// ---------------------------这是商品轮播图 最后要通过 图片逗号拼接
						this.videolist.push({
							url: res.data
						});
					}
				});
				console.log(this.videolist);
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible1 = true;
				console.log(file);
			},
			//轮播图移除图片
			handleRemove(file, fileList) {
				// fileList是剩下的照片
				this.imgList = fileList;
			},
			//轮播图上传
			uploadFile(param) {
				var file = param.file;
				const formData = new FormData();
				formData.append("file", file);
				upload(formData, param).then((res) => {
					if (res.code == 0) {
						// ---------------------------这是商品轮播图 最后要通过 图片逗号拼接
						this.imgList.push({
							url: res.data
						});
					}
				});
				console.log(this.imgList);
			},
			changeselect(val) {
				// console.log(val);
				this.form.servetypeid = val.id;
				this.form.servetype = val.name;
			},
			change() {},
			async gettypelist() {
				let result = await gettypelist();
				console.log(result);
				if (result.code == 0) {
					this.reqCategory1 = result.data;
				}
			},
			// 将富文本获取回来数据上剔除掉html标签
			getSimpleText(html) {
				var re1 = new RegExp("<.+?>", "g"); //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
				var msg = html.replace(re1, ""); //执行替换成空字符
				return msg;
			},
			add() {
				this.form = {
					copywritingtypeid: "",
					content: "",
					images: "",
					shtype: "",
					video: "",
				};
				this.qubie = 0;
				this.gettypelist();
				this.dialogFormVisible = true;
				this.imgList = [];
				this.videolist = [];
			},
			edit(val) {
				console.log("点击了编辑", val);
				this.form = {
					copywritingtypeid: "",
					content: "",
					images: "",
					shtype: "",
					video: "",
					label: ''
				};
				this.qubie = 1;
				this.imgList = [];
				console.log("图片", val.images);
				this.gettypelist();
				this.form = Object.assign(this.form, val);
				this.dialogFormVisible = true;
				this.imgList = [];
				this.videolist = [];
				if (val.video == "") {
					val.images.forEach((item) => {
						this.imgList.push({
							url: item
						});
					});
				} else {
					this.imgList = [];
					this.videolist.push({
						url: val.video
					});
				}
			},
			// 关闭
			handleClose() {
				this.dialogFormVisible = false;
				this.$emit("refresh");
			},

			async quedingtianjia() {
				if (this.qubie == 0) {
					// console.log(this.form.endtime);
					// var originalDate = new Date(this.form.endtime);
					// var year = originalDate.getFullYear();
					// var month = (originalDate.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，需要加1，然后确保两位数
					// var day = originalDate.getDate().toString().padStart(2, "0"); // 确保两位数
					// var formattedDateString = `${year}-${month}-${day}`;
					// console.log(formattedDateString);

					let param = {
						copywritingtypeid: this.form.copywritingtypeid,
						content: this.getSimpleText(this.form.content),
						images: this.form.images,
						shtype: this.form.shtype,
						video: this.form.video,
						label: this.form.label
					};
					console.log(param);
					let result = await addcopywritingadd(param);
					if (result.code == 0) {
						this.$message({
							message: `添加文案成功`,
							type: "success",
						});
						this.handleClose();
					}
				} else if (this.qubie == 1) {
					let param = {
						id: parseInt(this.form.id),
						copywritingtypeid: this.form.copywritingtypeid,
						content: this.getSimpleText(this.form.content),
						images: this.form.images,
						shtype: this.form.shtype,
						video: this.form.video,
						label: this.form.label
					};
					let result = await updatecopywritingupdate(param);
					if (result.code == 0) {
						this.$message({
							message: `修改文案成功`,
							type: "success",
						});
						this.handleClose();
					}
				}
			},
		},
		watch: {
			imgList: {
				handler(newVal) {
					// console.log("监听", newVal);
					// 这里创建新的数组 用逗号进行隔开 主要是接口要求
					let imagesarr = [];
					const result = newVal.map((item) => `${item.url}`).join(",");
					this.form.images = result;
					console.log("猪嗨", this.form.images);
				},
				deep: true,
			},
			videolist: {
				handler(newVal) {
					// console.log("监听", newVal);
					// 这里创建新的数组 用逗号进行隔开 主要是接口要求
					let imagesarr = [];
					const result = newVal.map((item) => `${item.url}`).join(",");
					this.form.video = result;
					console.log("猪嗨", this.form.video);
				},
				deep: true,
			},
		},
		computed: {
			titlecom() {
				if (this.qubie == 0) {
					return "添加文案";
				} else {
					return "修改文案";
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.specificationInput {
		width: 250px;
	}

	.avatar-uploader-icon[data-v-22a48a68] {
		border: 1px dashed #d9d9d9;
		width: 300px;
		height: 300px;
		display: flex;
		justify-content: center;
		flex-direction: column;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		width: 300px;
		height: 300px;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409eff;
	}

	.addguigeBtn {
		margin-left: 100px;
		margin-bottom: 22px;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 180px;
		height: 180px;
		line-height: 180px;
		text-align: center;
	}

	.avatar {
		width: 180px;
		height: 180px;
		display: block;
	}

	v-deep .el-upload--picture-card {
		width: 300px !important;
		height: 300px !important;
	}

	.specificationInput1 {
		width: 150px;
	}
</style>